package com.down.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Authenticator;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.HttpURLConnection;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DownloadFile {
	/**
	 * 从网络Url中下载文件
	 * 
	 * @param urlStr
	 * @param fileName
	 * @param savePath
	 * @throws IOException
	 */
	public static void downLoadFromUrl(String urlStr, String savePath, Map<String,String> map, Integer timeout, String fileName) throws IOException {
		//System.setProperty("proxyHost", "192.168.0.160");
		//System.setProperty("proxyPort", "1082");
		
		URL url = new URL(urlStr);
		//initProxy("192.168.0.160", 1082, "admin","123456");
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        //设置超时间
        conn.setConnectTimeout(timeout);
        //防止服务器默认的跳转
        conn.setInstanceFollowRedirects(false); 
        //防止屏蔽程序抓取而返回403错误
        for (Entry<String, String> entry : map.entrySet()) { 
        	conn.setRequestProperty(entry.getKey(), entry.getValue());
        }
        conn.connect();
		// 得到输入流
		InputStream inputStream = conn.getInputStream();
		// 获取自己数组
		byte[] getData = readInputStream(inputStream);

		// 文件保存位置
		File saveDir = new File(savePath);
		if (!saveDir.exists()) {
			saveDir.mkdir();
		}
		if (fileName != null) {
			Pattern p = Pattern.compile("\\s*|\t|\r|\n");
			Matcher m = p.matcher(fileName);
			fileName = m.replaceAll("");
		}
		File file = new File(saveDir + File.separator + fileName);
		FileOutputStream fos = new FileOutputStream(file);
		fos.write(getData);
		if (fos != null) {
			fos.close();
		}
		if (inputStream != null) {
			inputStream.close();
		}

		System.out.println("info:" + fileName +" download success");

	}

	/**
	 * 从输入流中获取字节数组
	 * 
	 * @param inputStream
	 * @return
	 * @throws IOException
	 */
	public static byte[] readInputStream(InputStream inputStream) throws IOException {
		byte[] buffer = new byte[1024];
		int len = 0;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		while ((len = inputStream.read(buffer)) != -1) {
			bos.write(buffer, 0, len);
		}
		bos.close();
		return bos.toByteArray();
	}
	/**
	 * 设置代理
	 * @param host
	 * @param port
	 * @param username
	 * @param password
	 */
	public static void initProxy(String host, int port, final String username, final String password) {
		Authenticator.setDefault(new Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(username,new String(password).toCharArray());
			}
		});
		System.setProperty("proxySet", "true");
		System.setProperty("proxyHost", host);
        System.setProperty("proxyPort", Integer.toString(port));
        System.setProperty("proxyType", "4");
        CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
    }
}
